﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.ComponentModel;

namespace eHouse
{
    public partial class Settings : PhoneApplicationPage
    {

        private bool loaded = false;
        private bool connecting = false;
        private bool alreadyStarted = false;
        BackgroundWorker connection;

        public Settings()
        {
            if ((Visibility)Application.Current.Resources["PhoneLightThemeVisibility"] == Visibility.Visible)
            {
                App.IconToUse = "Black";
            }

            InitializeComponent();
            if (!alreadyStarted)
            {
                Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated += RestartApp;
                alreadyStarted = true;
            }

            try
            {
                App.ConnectionManager = new ConnectionManager(OnConnectionToServerCompleted);
                this.Visibility = Visibility.Collapsed;
                loaded = true;
            }
            catch (InvalidOperationException)
            {
            }
        }

        private void RestartApp(object o, Microsoft.Phone.Shell.ActivatedEventArgs e)
        {
            WaitingScreen.fromDorm = true;
            Dispatcher.BeginInvoke(() =>
            {
                NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
            });
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            bool hasNetworkConnection = NetworkInterface.GetIsNetworkAvailable();
            if (!hasNetworkConnection)
            {
                this.Visibility = Visibility.Collapsed;
                MessageBox.Show("To use the eHouse remote system you need an active network connection. Enable your Internet access and try again");
                App.Quit();
            }

            if (loaded)
            {
                Navigate();
            }
            else
            {
                ipBox.Focus();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            bool valid = false;
            IPAddress ip;
            if (!string.IsNullOrEmpty(ipBox.Text))
            {
                valid = IPAddress.TryParse(ipBox.Text, out ip);
            }

            if (!valid)
            {
                MessageBox.Show("The provided IP has not the correct format");
                return;
            }

            SwitchScreenState();

            string ipText = ipBox.Text;
            connection = new BackgroundWorker();
            connection.WorkerSupportsCancellation = true;
            connection.DoWork += new DoWorkEventHandler((object send, DoWorkEventArgs dwea) =>
            {
                connecting = true;
                App.ConnectionManager = new ConnectionManager(ipText, OnConnectionToServerCompleted);
            });
            connection.RunWorkerAsync();
        }

        private void SwitchScreenState()
        {
            Dispatcher.BeginInvoke(() =>
            {
                Connect.IsEnabled = !Connect.IsEnabled;
                Connect.Content = ((string)(Connect.Content)) == "Connect" ? "Connecting" : "Connect";
                Progress.Visibility = (Progress.Visibility == Visibility.Collapsed) ? Visibility.Visible : Visibility.Collapsed;
            });
        }

        private void OnConnectionToServerCompleted(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                connecting = false;
                string mes = "";
                if (App.ConnectionManager == null)
                {
                    mes += "the IP and ";
                }
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("An error occurred connecting to the eHouse device. Check " + mes + "the internet connection and try again");
                    if (App.ConnectionManager != null)
                    {
                        App.Quit();
                    }
                });
                SwitchScreenState();
                return;
            }
            if (connecting)
            {
                connecting = false;
                App.ConnectionManager.SaveSettings();
                Navigate();
            }
        }

        private void Navigate()
        {
            Dispatcher.BeginInvoke(() =>
            {
                //WaitingScreen.nextWindow = "/MainPage.xaml";
                WaitingScreen.nextWindow = WaitingScreen.savedWindow;
                WaitingScreen.waitingTask = new WaitingScreen.WaitingTask(() =>
                {
                    App.ViewModel.LoadData();
                });
                NavigationService.Navigate(new Uri("/WaitingScreen.xaml", UriKind.RelativeOrAbsolute));
            });

        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (connecting)
            {
                connecting = false;
                connection.CancelAsync();
                SwitchScreenState();
                e.Cancel = true;
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            NavigationService.RemoveBackEntry();
        }
    }
}